package com.icoolkj.learn.juc.base;

import lombok.extern.slf4j.Slf4j;

/**
 * @author icoolkj
 * @version 1.0
 * @description 线程终止案例： 线程 stop 方法，建议不要使用，存在很多问题
 * @createDate 2025/03/04 13:19
 */
@Slf4j
public class ThreadStopDemo {
    private static final Object lock = new Object();
    private static int account1 = 10000;
    private static int account2 = 0;

    public static void main(String[] args) {
        Thread threadA = new Thread(new TransferTask(), "threadA");
        threadA.start();

        // 等待线程 A 开始执行
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        threadA.stop();

        // 验证锁是否释放
        synchronized (lock) {
            log.info("main 加锁成功...");
        }

    }

    private static class TransferTask implements Runnable {
        @Override
        public void run() {
            try {
                synchronized (lock) {
                    log.info("开始转账...");
                    // 1号账户减少 1000
                    account1 -= 1000;
                    log.info("1号账户余额：{}", account1);
                    // 休眠 1 秒
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    // 2号账户增加 100
                    account2 += 100;
                    log.info("2号账户余额：{}", account2);
                    log.info("转账结束...");
                }
            }catch (Throwable e) {
                log.info("{} 线程结束执行", Thread.currentThread().getName());
                log.error(e.getMessage(), e);
                e.printStackTrace();
            }
        }
    }
}
